package com.dmzc.stage2.chapter17;

import static java.lang.Thread.currentThread;

/***
 * ReadWriteLock测试，实质上是对共享资源的读写进行了封装，
 * 将读、写绑定在同一个锁上，只在获取锁和释放锁的时同步
 */
public class ReadWriteLockTest {
    private final static String text = "this is a example for readwrite lock";

    public static void main(String[] args) {
        final ShareData shareData = new ShareData(100);
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int index = 0; index < text.length(); index++) {

                    try {
                        char c = text.charAt(index);
                        shareData.write(c);
                        System.out.println(currentThread() + "write" + c);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                while (true){
                    try {
                        System.out.println(currentThread()+"read"+ new String(shareData.read()));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
